package com.cinc.mdm.modules.bom.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinc.mdm.constant.MdmConstant;
import com.cinc.mdm.modules.bom.entity.MdmBom;
import com.cinc.mdm.modules.bom.entity.MdmBomDetail;
import com.cinc.mdm.modules.bom.service.IMdmBomDetailService;
import com.cinc.mdm.modules.bom.service.IMdmBomService;
import com.cinc.mdm.modules.bom.vo.MdmBomPage;
import com.cinc.mdm.modules.bom.vo.MdmBomTreePage;
import com.cinc.mdm.modules.codeRule.service.IMdmCodeRuleService;
import com.cinc.mdm.modules.material.entity.MdmMaterial;
import com.cinc.mdm.modules.material.mapper.MdmMaterialMapper;
import com.cinc.mdm.modules.material.service.IMdmMaterialService;
import com.cinc.mdm.modules.sysParam.entity.MdmSysParam;
import com.cinc.mdm.modules.sysParam.service.IMdmSysParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: bom主记录
 * @Author: jeecg-boot
 * @Date: 2021-10-24
 * @Version: V1.0
 */
@Api(tags = "bom主记录")
@RestController
@RequestMapping("/mdm/bom")
@Slf4j
public class MdmBomController {
    @Autowired
    private IMdmBomService mdmBomService;
    @Autowired
    private IMdmBomDetailService mdmBomDetailService;
    @Autowired
    private IMdmMaterialService mdmMaterialService;

    /**
     * 分页列表查询
     *
     * @param mdmBomPage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "bom主记录-分页列表查询")
    @ApiOperation(value = "bom主记录-分页列表查询", notes = "bom主记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MdmBomPage mdmBomPage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<MdmBomPage> page = new Page<MdmBomPage>(pageNo, pageSize);
        IPage<MdmBomPage> pageList = mdmBomService.pageList(page, mdmBomPage);
        return Result.OK(pageList);
    }

    /**
     * 树形查询查询
     *
     * @param materialDesc
     * @return
     */
    @AutoLog(value = "bom树查询")
    @ApiOperation(value = "bom树查询", notes = "bom树查询")
    @GetMapping(value = "/treeList")
    public Result<?> treeList(@RequestParam(value = "materialDesc", required = false) String materialDesc,
                              @RequestParam(value = "materialTypeCode", required = false) String materialTypeCode,
                              @RequestParam("levelType") String levelType) {
        List<MdmBomTreePage> treeList = mdmBomService.queryTreeList(materialDesc, materialTypeCode, levelType);
        return Result.OK(treeList);
    }

    /**
     * 多级BOM列表查询
     *
     * @param mdmBomPage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "多级BOM列表查询")
    @ApiOperation(value = "多级BOM列表查询", notes = "多级BOM列表查询")
    @GetMapping(value = "/multiLevelList")
    public Result<?> multiLevelList(MdmBomPage mdmBomPage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page page = new Page<>(pageNo, 1);
        IPage pageList = mdmBomService.findMultiLevelList(page, mdmBomPage);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mdmBomPage
     * @return
     */
    @AutoLog(value = "bom主记录-添加")
    @ApiOperation(value = "bom主记录-添加", notes = "bom主记录-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MdmBomPage mdmBomPage) {
        MdmBom mdmBom = new MdmBom();
        BeanUtils.copyProperties(mdmBomPage, mdmBom);
        mdmBomService.saveMain(mdmBom, mdmBomPage.getMdmBomDetailList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mdmBomPage
     * @return
     */
    @AutoLog(value = "bom主记录-编辑")
    @ApiOperation(value = "bom主记录-编辑", notes = "bom主记录-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MdmBomPage mdmBomPage) {
        MdmBom mdmBom = new MdmBom();
        BeanUtils.copyProperties(mdmBomPage, mdmBom);
        MdmBom mdmBomEntity = mdmBomService.getById(mdmBom.getId());
        if (mdmBomEntity == null) {
            return Result.error("未找到对应数据");
        }
        mdmBomService.updateMain(mdmBom, mdmBomPage.getMdmBomDetailList(), mdmBomPage.getMdmBomDetailDeleteIdList(), mdmBomPage.getMdmBomDetailAddIdList());
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param mdmBomTreePage
     * @return
     */
    @AutoLog(value = "bom树-编辑")
    @ApiOperation(value = "bom树-编辑", notes = "bom树-编辑")
    @PutMapping(value = "/treeEdit")
    public Result<?> treeEdit(@RequestBody MdmBomTreePage mdmBomTreePage) {
        mdmBomService.updateTree(mdmBomTreePage);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "bom主记录-通过id删除")
    @ApiOperation(value = "bom主记录-通过id删除", notes = "bom主记录-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mdmBomService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "bom主记录-批量删除")
    @ApiOperation(value = "bom主记录-批量删除", notes = "bom主记录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mdmBomService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "bom主记录-通过id查询")
    @ApiOperation(value = "bom主记录-通过id查询", notes = "bom主记录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MdmBom mdmBom = mdmBomService.getById(id);
        if (mdmBom == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mdmBom);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "bom明细通过主表ID查询")
    @ApiOperation(value = "bom明细主表ID查询", notes = "bom明细-通主表ID查询")
    @GetMapping(value = "/queryMdmBomDetailByMainId")
    public Result<?> queryMdmBomDetailListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<MdmBomDetail> mdmBomDetailList = mdmBomDetailService.selectByMainId(id);
        return Result.OK(mdmBomDetailList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mdmBomPage
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MdmBomPage mdmBomPage) {
        // Step.1 组装查询条件查询数据
//      QueryWrapper<MdmBom> queryWrapper = QueryGenerator.initQueryWrapper(mdmBom, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<MdmBomPage> queryList = mdmBomService.listBom(mdmBomPage);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<MdmBomPage> mdmBomPageList = new ArrayList<>();
        if (oConvertUtils.isEmpty(selections)) {
            mdmBomPageList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            mdmBomPageList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<MdmBomPage> pageList = new ArrayList<MdmBomPage>();
        for (MdmBomPage main : mdmBomPageList) {
            MdmBomPage vo = new MdmBomPage();
            BeanUtils.copyProperties(main, vo);
            List<MdmBomDetail> mdmBomDetailList = mdmBomDetailService.selectByMainId(main.getId());
            vo.setMdmBomDetailList(mdmBomDetailList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "bom列表");
        mv.addObject(NormalExcelConstants.CLASS, MdmBomPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("bom数据", "导出人:" + sysUser.getRealname(), "bom列表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MdmBomPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MdmBomPage.class, params);
                if (oConvertUtils.listIsNotEmpty(list)) {
                    mdmBomService.saveBatchMain(list);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 通过excel导入并更新数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importUpdExcel", method = RequestMethod.POST)
    public Result<?> importUpdExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MdmBomPage> list = ExcelImportUtil.importExcel(file.getInputStream(), MdmBomPage.class, params);
                if (oConvertUtils.listIsNotEmpty(list)) {
                    mdmBomService.saveOrUpdBatchMain(list);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }
}
